<template>
  <div class="mall">
    <h2>商城</h2>
    <p class="intro">
      精选优质商品，提供卓越的购物体验。您可以查看和收藏商品。
    </p>

    <div class="search-container">
      <label for="searchQuery" style="margin-right: 10px; width: 150px;">名称搜索:</label>
      <el-input v-model="searchQuery" placeholder="搜索商品名称..." suffix-icon="el-icon-search" clearable
        @clear="fetchProducts" @input="fetchProducts" style="width: 300px; margin-bottom: 20px;" />
      <label for="selectedCategory" style="margin-right: 10px;width: 150px;">类型筛选:</label>
      <el-select v-model="selectedCategory" placeholder="选择商品类别" @change="fetchProducts" style="margin-bottom: 20px;">
        <el-option v-for="category in categories" :key="category.id" :label="category.type" :value="category.id" />
      </el-select>
    </div>

    <div class="product-list">
      <div v-for="product in products" :key="product.id" class="product-card">
        <img :src="product.image" alt="商品图片" class="product-image" />
        <h4>{{ product.name }}</h4>
        <p class="description">{{ product.description }}</p>
        <p class="price">价格: ￥{{ product.price.toFixed(2) }}</p>
        <div class="button-group">
          <el-button plain @click="openTransactionModal(product)" type="primary">立即交易</el-button>
          <!-- 收藏 -->

          <el-button @click="open" type="primary">加入购物车</el-button>
          <el-button @click="addFavorites(product)" type="warning" :icon="Star" circle />
        </div>
      </div>
    </div>
    <div class="pagination">
      <el-pagination @current-change="handlePageChange" :current-page="currentPage" :page-size="pageSize"
        :total="totalProducts" layout="prev, pager, next"></el-pagination>
    </div>



    <el-dialog v-model="isTransactionModalVisible" title="交易信息">
      <el-form :model="transactionProduct" ref="transactionForm">
        <el-form-item label="备注信息">
          <el-input v-model="transactionProduct.remark" placeholder="输入备注信息"></el-input>
        </el-form-item>
        <el-form-item label="交易时间">
          <el-date-picker v-model="transactionProduct.transactionTime" type="datetime"
            placeholder="选择交易时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="可交易地点">
          <el-select v-model="transactionProduct.transactionLocation" placeholder="选择交易地点" multiple>
            <el-option v-for="location in locations" :key="location.id" :label="location.name" :value="location.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isTransactionModalVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmTransaction">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getOtherGoodsList, listProducts, listOtherProductsByPage } from "@/api/product"; // 假设存在的 API
import { buyerCreateTransaction } from "@/api/transactionRecord"; // 假设存在的 API
import { listFacilities } from "@/api/facility"; // 假设存在的 API
import { listProductTypes } from "@/api/productType"; // 假设存在的 API
import {checkIfFavorite,addFavorite } from "@/api/favorite"; // 假设存在的 API
import { ElMessage, ElMessageBox, formContextKey } from 'element-plus';
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
  Star,
} from '@element-plus/icons-vue'

import { useRouter } from 'vue-router';

const router = useRouter();
const hasToken = () => localStorage.getItem('token') !== null;

const products = ref([]);
const isTransactionModalVisible = ref(false);
const searchQuery = ref('');
const selectedCategory = ref(null);
const currentPage = ref(1);
const pageSize = ref(10);
const totalProducts = ref(0);
const categories = ref([]);
const locations = ref([]);

const transactionProduct = ref({
  id: 0,
  storeId: 0,
  status: 0,
  remark: '',
  transactionTime: null,
  transactionLocation: [],
});

const fetchProducts = () => {
  const params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    keywords: searchQuery.value,
    productTypeId: selectedCategory.value,
  };

  listOtherProductsByPage(params).then(res => {
    products.value = res.data.list;
    // totalProducts.value = res.data.total;
  });
};

const handlePageChange = (page) => {
  currentPage.value = page;
  fetchProducts();
};

const getCategories = () => {
  categories.value = [
  ];

  listProductTypes().then(res => {
    categories.value = res.data;
  });




};

const getProducts = () => {
  if (localStorage.getItem("token")) {
    getOtherGoodsList().then(res => {
      products.value = res.data;
    });
  } else {
    listProducts().then(res => {
      products.value = res.data;
    });
  }
};

const openTransactionModal = (product) => {
  if (!hasToken()) {
    ElMessage({ type: 'error', message: '请先登录' });
  } else {
    isTransactionModalVisible.value = true;
    transactionProduct.value = product;
  }
};

const confirmTransaction = () => {
  const params = {
    productId: transactionProduct.value.id,
    storeId: transactionProduct.value.storeId,
    productStatus: transactionProduct.value.status,
    remark: transactionProduct.value.remark,
    transactionTime: transactionProduct.value.transactionTime,
    transactionLocation: transactionProduct.value.transactionLocation,
  };

  buyerCreateTransaction(params).then(res => {
    if (res.code === 200) {
      ElMessage({ type: 'success', message: '交易请求已发送，请等待卖家确认' });
      isTransactionModalVisible.value = false;
      transactionProduct.value = {};
    } else {
      ElMessage({ type: 'error', message: '交易失败，请重试' });
    }
  }).catch(() => {
    ElMessage({ type: 'error', message: '服务器出错，请稍后再试' });
  });
};

const getFacilities = async () => {
  const res = await listFacilities();
  if (res.code === 200) {
    locations.value = res.data;
  } else {
    ElMessage({ type: 'error', message: '获取设施失败，请稍后再试' });
  }
};

//收藏
const addFavorites = async (product) => {
  if (!hasToken()) {
    ElMessage({ type: 'error', message: '请先登录' });
    return;
  }

  // 查询是否已收藏
  const res = await checkIfFavorite(product.id);
  if(res.code === 200){
   const isFavorite = res.data;
    if (isFavorite) {
    ElMessage({ type: 'info', message: '你已收藏该商品' });
    return;
  }
  }
  // 弹出确认框
  ElMessageBox.confirm('确认要收藏该商品吗？', '确认收藏', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    // 执行收藏操作
    await addFavorite(product.id);
    ElMessage({ type: 'success', message: '商品已成功收藏' });
  }).catch(() => {
    ElMessage({ type: 'info', message: '取消收藏' });
  });
};






onMounted(() => {
  getProducts();
  getCategories();
  getFacilities();
});
</script>

<style scoped>
.mall {
  width: 95vw;
  /* 全屏宽度 */
  height: 100vh;
  /* 全屏高度 */
  padding: 20px;
  background-color: #f8f9fa;
  overflow-y: auto;
  /* 允许纵向滚动 */
}

h2 {
  font-family: 'Georgia', serif;
  color: #4a4a4a;
  font-size: 2.5em;
  margin-bottom: 10px;
  text-align: center;
  /* 居中对齐 */
}

.intro {
  font-size: 1.2em;
  color: #777;
  text-align: center;
  /* 居中对齐 */
  margin-bottom: 30px;
}

.search-container {
  display: flex;
  width: 700px;
  justify-content: space-between;
  margin-bottom: 20px;
}


.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;

}

.product-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  /* 自适应网格布局 */
  gap: 20px;
  /* 卡片间距 */
  padding: 0;
  /* 消除内边距 */
  margin-top: 20px;
  /* 上方间距 */
}

.product-card {
  border: 1px solid #ddd;
  border-radius: 10px;
  background-color: #fff;
  padding: 20px;
  transition: transform 0.3s, box-shadow 0.3s;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  text-align: center;
  /* 居中对齐 */
  font-size: 15px;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
}

.product-image {
  width: 100%;
  /* 图片宽度自适应 */
  height: auto;
  /* 高度自适应 */
  border-radius: 10px;
  /* 圆角 */
  margin-bottom: 10px;
  /* 图片与下方内容间距 */
}

.description {
  font-size: 0.9em;
  color: #555;
  margin: 10px 0;
}

.price {
  font-size: 1em;
  color: #e67e22;
  /* 使用橙色突出价格 */
  margin: 10px 0;
}

.button-group {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}
</style>